from flask import Flask, render_template, redirect, url_for, request, jsonify, session
from functools import wraps
from DataBiz import DataBiz
import os
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'your-secret-key-here-change-in-production'

# if __name__ == '__main__':
#     # 开启调试模式：自动重载+详细错误页面
#     app.run(debug=True)

# 创建DataBiz实例
data_biz = DataBiz()

# 登录验证装饰器
def login_required(f):
    """登录验证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function
# 添加CORS支持

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

@app.route('/')
@login_required
def index():
    """主页路由"""
    return render_template('index.html')

@app.route('/index')
@login_required
def index_alt():
    """主页路由（备用路径）"""
    return render_template('index.html')

@app.route('/login')
def login():
    """登录页面路由"""
    return render_template('login.html')

@app.route('/api/login', methods=['POST'])
def api_login():
    """登录验证API"""
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
    
    if data_biz.validate_user(username, password):
        session['username'] = username  # 记录登录状态
        return jsonify({'success': True, 'message': '登录成功'})
    else:
        return jsonify({'success': False, 'message': '用户名或密码错误'}), 401

@app.route('/logout')
def logout():
    """登出功能"""
    session.pop('username', None)
    return redirect(url_for('login'))

@app.route('/api/platforms')
def platforms():
    """获取所有平台数据"""
    platforms_data = data_biz.get_platforms()
    return jsonify(platforms_data)

@app.route('/api/stores/<platform>')
def stores(platform):
    """根据平台获取店铺数据"""
    store_list = data_biz.get_stores_by_platform(platform)
    return jsonify(store_list)

@app.route('/api/accounts')
@login_required
def accounts():
    """获取所有账套数据"""
    account_list = data_biz.get_accounts()
    return jsonify(account_list)

@app.route('/import.html')
@login_required
def import_page():
    """数据导入页面"""
    return render_template('import.html')

@app.route('/import-modal.html')
@login_required
def import_modal():
    return render_template('import-modal.html')

@app.route('/cost-modal.html')
@login_required
def cost_modal():
    return render_template('cost-modal.html')

@app.route('/zyb.html')
@login_required
def zyb_page():
    """作业帮页面"""
    return render_template('zyb.html')

@app.route('/api/tables')
@login_required
def tables():
    """获取所有数据表信息"""
    try:
        tables_list = data_biz.get_tables()
        return jsonify(tables_list)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/tablesofcost')
@login_required
def tablesofcost():
    """获取所有数据表信息"""
    try:
        tables_list = data_biz.get_cost_tables()
        return jsonify(tables_list)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/save-task', methods=['POST'])
@login_required
def save_task():
    """保存任务到kd_task表"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['table_name',  'start_time', 'end_time']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'success': False, 'message': f'{field}不能为空'}), 400
        
        table_name = data.get('table_name')
        plat_id = data.get('plat_id','') # 可以为空
        shop_id = data.get('shop_id', '')  # 可以为空
        start_time = data.get('start_time')
        end_time = data.get('end_time')
        
        # 保存任务
        operate_type = data.get('operate_type')
        remark = data.get('remark', '')
        result = data_biz.save_task(table_name, plat_id, shop_id, start_time, end_time, operate_type, remark)
        
        return jsonify(result)
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/operate-types')
@login_required
def get_operate_types():
    """获取所有操作类型（导入规则）"""
    try:
        operate_types = data_biz.get_operate_types()
        return jsonify(operate_types)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/tasks')
@login_required
def get_tasks():
    """获取任务列表，支持分页和过滤条件"""
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))
        
        # 获取过滤参数
        table_name = request.args.get('table_name')
        plat_id = request.args.get('plat_id')
        shop_id = request.args.get('shop_id')
        start_time_start = request.args.get('start_time_start')
        start_time_end = request.args.get('start_time_end')
        operate_type = request.args.get('operate_type')
        run_flag = request.args.get('run_flag')
        remark_like = request.args.get('remark_like')
        category = 'income'
        
        # 调用DataBiz的get_tasks方法，传入过滤参数
        result = data_biz.get_tasks(
            page=page,
            page_size=page_size,
            table_name=table_name,
            plat_id=plat_id,
            shop_id=shop_id,
            start_time_start=start_time_start,
            start_time_end=start_time_end,
            operate_type=operate_type,
            run_flag=run_flag,
            remark_like=remark_like,
            category=category
        )
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/tasksofcost')
@login_required
def get_cost_tasks():
    """获取任务列表，支持分页和过滤条件"""
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))

        # 获取过滤参数
        table_name = request.args.get('table_name')
        plat_id = request.args.get('plat_id')
        shop_id = request.args.get('shop_id')
        start_time_start = request.args.get('start_time_start')
        start_time_end = request.args.get('start_time_end')
        operate_type = request.args.get('operate_type')
        run_flag = request.args.get('run_flag')
        remark_like = request.args.get('remark_like')
        category = 'cost'

        # 调用DataBiz的get_tasks方法，传入过滤参数
        result = data_biz.get_tasks(
            page=page,
            page_size=page_size,
            table_name=table_name,
            plat_id=plat_id,
            shop_id=shop_id,
            start_time_start=start_time_start,
            start_time_end=start_time_end,
            operate_type=operate_type,
            run_flag=run_flag,
            remark_like=remark_like,
            category=category
        )
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/sync-kingdee', methods=['POST'])
@login_required
def sync_kingdee():
    """同步金蝶任务API"""
    try:
        data = request.get_json()
        task_id = data.get('task_id')
        
        if not task_id:
            return jsonify({'success': False, 'message': '任务ID不能为空'}), 400
        
        # 调用DataBiz的同步方法
        result = data_biz.sync_kingdee_task(task_id)
        
        return jsonify(result)
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/test', methods=['POST'])
@login_required
def api_test():
    """测试验证API"""
    try:
        data = request.get_json()
        timestamp = data.get('timestamp')
        message = data.get('message')
        
        print(f"收到测试验证请求 - 时间: {timestamp}, 消息: {message}")
        
        # 返回测试成功的响应
        return jsonify({
            'success': True,
            'message': f'测试验证成功 - 收到时间: {timestamp}',
            'received_data': {
                'timestamp': timestamp,
                'message': message
            },
            'server_time': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/cost.html')
@login_required
def cost_page():
    return render_template('cost.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8080)